package com.ruoyi.kis.controller;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult_KIS;
import com.ruoyi.kis.Vars.Constants;
import com.ruoyi.kis.annotaion.BasicAuthCheck;
import com.ruoyi.kis.domain.OsInWareOrderF;
import com.ruoyi.kis.domain.OutSourceEntryF;
import com.ruoyi.kis.service.IKisService;
import com.ruoyi.kis.util.HttpSendWmsUtil;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.*;

/**
 * @Author: zhanglm
 * @CreateDate: 2025-02-19 10:16
 * @FullNameClass: com.ruoyi.kis.controller.KisOsInWareOrder
 * @Description: 收料通知单、外购入库单的接口；收料通知单：ERP(POINstock)》WMS，外购入库单：WMS>ERP(ICStockBill)
 */
@RestController
@RequestMapping("/kiswgrkd")
@Component("kiswglkd")
@Api("kis接口")
public class KisWGlkdController extends BaseController {
    @Autowired
    private IKisService kisService;
    private static final Logger LOGGER = LoggerFactory.getLogger(KisWGlkdController.class);

    /**
     * 外购入库单反馈
     *  @return
     *  WMS >ERP
     *
     */
    @RequestMapping("/wgrkdfeedback")
    @BasicAuthCheck
    public AjaxResult_KIS queryItems(@RequestBody @Valid OsInWareOrderF osInWareOrderF)  {

        if (osInWareOrderF == null){
            return AjaxResult_KIS.error("error","空数据");
        }
        LOGGER.info("外购入库单接收json："+osInWareOrderF);
        Map map = kisService.saveOsInWareOrder(osInWareOrderF);
        JSON parse = JSONUtil.parse(osInWareOrderF);
        String s =  parse.toString();
        System.out.println("WMS过来的值：" + s);
        if (map.get("MSGCODE").equals("1")){
            return AjaxResult_KIS.error("error",map.get("MSG").toString());
        }else {
            return AjaxResult_KIS.success("success","");
        }
    }
    /**
     * 收料通知单（外购入库单）,对方只接收单条记录
     * @return
     *
已废弃，将功能移动到KisSLTZDController下
     *  ERP > WMS
     * 状态：完成
     *
     */
    @RequestMapping("/wgrkd")
    public AjaxResult_KIS queryItems()  {

//        Date orderTime = kisService.queryCurrentTime(Constants.OUT_SOURCE_IN_WARE_ORDER);
        List<OutSourceEntryF> outSourceEntryFList = kisService.queryOutSourceInWareOrder();
        if (outSourceEntryFList == null || outSourceEntryFList.isEmpty() || outSourceEntryFList.size() == 0){
            return AjaxResult_KIS.error("error","未查询到相关单据");
        }

        String s = "";
        if (outSourceEntryFList != null && outSourceEntryFList.size() > 0){
            s = JSONUtil.parse(outSourceEntryFList.get(0)).toString();
            try {
//                String msg = HttpUtil.post(Constants.OUT_SOURCE_IN_WARE_ORDER_URL,s);
                String msg = HttpSendWmsUtil.sendWms(Constants.OUT_SOURCE_IN_WARE_ORDER_URL,s);
                LOGGER.info("收料通知单（外购入库单）发送json："+s);
//                {"msgcode":"1","msgname":"接口调用失败:com.foreris.eris.common.exception.BusinessException:ERP下发外购入库订单号[SLTZ20250118001]已存在\n","msg":"接口调用失败:com.foreris.eris.common.exception.BusinessException:ERP下发外购入库订单号[SLTZ20250118001]已存在\n"}
                if (msg != null && !msg.isEmpty()){
                    JSONObject entries = JSONUtil.parseObj(msg);
                    String msgcode = entries.get("msgcode").toString();
                    String msgInfo = entries.get("msg").toString();
                    String kisFlag ;
                    if (msgcode.equals(Constants.ZHIKU.MSGCODE_SUCCESS) ||
                            (msgcode.equals(Constants.ZHIKU.MSGCODE_FAILURE) && msgInfo.contains("已存在"))){
                        kisFlag = Constants.ZHIKU.KISFLAG_SUCCESS;
                    }else {
                        kisFlag = Constants.ZHIKU.KISFLAG_FAILURE;
                    }
                    int countUpdate = kisService.updateKisPOInstockFlag(outSourceEntryFList.get(0).getFInterID(),kisFlag);
                    LOGGER.info("更新单据:{}状态kisFlag：{},{}条,反馈：{}",outSourceEntryFList.get(0).getFBillNo(),kisFlag,countUpdate,msg);
                }
            }catch (HttpException e){
                LOGGER.info("外购入库单："+e.getMessage());
                return AjaxResult_KIS.error();
            }
        }

        return AjaxResult_KIS.success("OK",outSourceEntryFList);
    }

}
